const _ = require('lodash');
const async = require('async');
const services = require('../../services');

const commonService = services.common;
const adminService = services.admin;

function initPage(req, res, callback) {
  getList(req, res, callback);
}

function getList(req, res, callback) {
  const params = req.query;
  const pageId = params.pageId;
  async.parallel({
    dictionaryList: async.apply(adminService.dictionary.getList, params),
    formList: async.apply(adminService.dictionary.getAllEnableForms, params),
    pageTotal: async.apply(adminService.dictionary.getPageTotal, params),
  }, (error, result) => callback(error, _.assign(result, { pageId })));
}

function saveDetail(req, res, callback) {
  const { SysDictionary: dictionaryModel } = commonService.getModels();
  const params = req.body;
  params.id = params.id == 0 ? null : params.id;
  const saveDetail = (next) => {
    dictionaryModel.upsert(params, next);
  };
  async.waterfall([saveDetail], callback);
}

function deleteDetail(req, res, callback) {
  const { SysDictionary: dictionaryModel } = commonService.getModels();
  const id = req.body.id;
  const deleteDetail = (next) => {
    dictionaryModel.update({ id }, { deleted: true }, next);
  };
  async.waterfall([deleteDetail], callback);
}

module.exports = {
  initPage,
  getList,
  saveDetail,
  deleteDetail,
};
